package br.edu.ifrn.tads.pontos.o;

import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity {

	EditText login,senha;
	CheckBox manterConexao;
	SharedPreferences prefs;
	SharedPreferences.Editor prefsEditor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

//		final ActionBar actionBar = getActionBar();
//		actionBar.setDisplayUseLogoEnabled(true);
		//		actionBar.set(true);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefsEditor = prefs.edit();

		login = (EditText) findViewById(R.id.edLoginEmail);
		senha = (EditText) findViewById(R.id.edSenha);
		manterConexao = (CheckBox) findViewById(R.id.ckbManter);

		login.setText(prefs.getString("email", ""));
		
		if (!prefs.getString("senha", "").equals("")){
			Intent intent = new Intent(getBaseContext(), PontosWebActivity.class);
			intent.putExtra("email", login.getText().toString());
			intent.putExtra("senha", prefs.getString("senha", ""));
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		}
	}


	public void efetuarLogin(View view){
		if (login.getText().length()==0 || senha.getText().length()==0)
			new AlertDialog.Builder(this).setMessage(R.string.errologinincompleto)
			.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create()
			.show();
		else{
			LoginTask lt = new LoginTask();
			lt.execute(login.getText().toString(),senha.getText().toString());
		}
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean>{

		private ProgressDialog progresso;
		private String email,senha;

		//Antes de Executar exibe uma janela de progresso
		protected void onPreExecute() {
			progresso = ProgressDialog.show(MainActivity.this, getString(R.string.app_name), "Por favor, Aguarde!");

		}

		//busca em segundo plano os usuarios
		protected Boolean doInBackground(String... arg) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpPost poster = new HttpPost(Globals.SERVER_URL+"/application/login");
				MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);          
				poster.addHeader("mobile", "yes");
				entity.addPart("login", new StringBody(email=arg[0],Charset.forName(HTTP.UTF_8)));
				entity.addPart("senha", new StringBody(senha=arg[1],Charset.forName(HTTP.UTF_8)));
				poster.setEntity(entity);
				HttpResponse response = client.execute(poster,Globals.getGlobalHttpContextInstance());
				HttpEntity respEntity = response.getEntity();
				String responseString = EntityUtils.toString(respEntity);
				Log.e("login", responseString);
				return responseString.equalsIgnoreCase("true");
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}

		//se o usuario foi encontrado, chama uma nova activity
		protected void onPostExecute(Boolean resultado) {
			AlertDialog.Builder alerta = new AlertDialog.Builder(MainActivity.this);
			alerta
			.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			if(resultado){
				Intent intent = new Intent(getBaseContext(), PontosWebActivity.class);
				intent.putExtra("email", email);
				intent.putExtra("senha", senha);
				prefsEditor.putString("email", email);
				if (manterConexao.isChecked())
					prefsEditor.putString("senha", senha);
				else
					intent.putExtra("backtologin", true);
				prefsEditor.commit();
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
			}
			else {
				alerta.setMessage("Verifique seu login e senha, e então tente novamente.");
				alerta.show();
			}


			this.progresso.dismiss();
			super.onPostExecute(resultado);

		}
	}
}
